var crypto = require('crypto');

module.exports = function(){
	var roles = {
			admin : 'admin',
			premmember : 'premmember',
			member : 'member',
			guest : 'guest'
	}
	var users = {
		bolu : {
			name : 'bolu',
			salt : 'randomly-generated-salt',
			pass : hash('bolu', 'randomly-generated-salt'),
			role : 'admin'
		},
		fischeversenker : {
			name : 'fischeversenker',
			salt : '',
			pass : hash('fischeversenker', ''),
			role : 'member' 
		},
	};

	/**
	 * hier stehen dann alle user drin die eingeloggt sind
	 * @todo timeout einbauen
	 */
	var authUsers = {};
	
	/**
	 * Used to generate a hash of the plain-text password + salt
	 */
	function hash(msg, key) {
		return crypto.createHmac('sha256', key).update(msg).digest('hex');
	}
	
	
	
	/**
	 * @param name string
	 * @param pass string
	 * @param fn callback(err, user)
	 */
	var authenticate = function(name, pass, fn){
		  if (!module.parent) console.log('authenticating %s:%s', name, pass);
		  var user = users[name];//db dumb hollen
		  if (!user) return fn(new Error('cannot find user'));
		  if (user.pass == hash(pass, user.salt)) return fn(null, user);
		  fn(new Error('invalid password'));
	};
	var restrictTo = function(role){
		return function(req, res, next){
			if(req.session.user){
				if(req.session.user.role == role){
					next();
				}else{
					//redirect oder error .... error heißt wir müssen es im controller machen
					res.redirect('/denied');
					//next(new Error('Access denied!'));
				}
			}else{
				//curr url mitgeben
				res.redirect('/login');
			}
		};
	};
	var login = function(req, res){
		authenticate(req.body.user, req.body.pass, function(err, user){
			if (user) {
				authUsers[user.name] = user;
				req.session.regenerate(function(){
					console.log("login passt");
					req.session.user = user;
					console.log(req.sessionID);
					// todo
					res.redirect('/player');
				});
			}else{
				// todo
				console.log("login fail");
				req.session.error = 'Authentication failed!!';
				res.redirect('login');
			}
	  });
	};
	var logout = function(req, res){
		authUsers[req.session.user.name] = null;
		req.session.destroy(function(){
			res.redirect('/');
		});
	};
	/**
	 * returns a reference object (auth return)
	 */
	return {
		authenticate: authenticate,
		restrictTo: restrictTo,
		login: login,
		logout: logout,
	};
};



